<?php
namespace Home\Controller;
use Think\Controller;
class UsersController extends Controller {
  
    public function reg(){
    	$userdata=$this->getAuthorizedUserLoginInfo();
    	$uid=I("uid");  //推广者用户id
    	
    	$openid=$userdata["openid"];
    	//查询表中是否存数据表中
    	$members_info=D("Members")->where(array("username"=>$openid))->find();
    	if(!empty($members_info)){
    		if(!empty($members_info["mobile"])){
    			//放入session 中去
    			session("uid",$members_info["uid"]);
    			$this->redirect("index");
    		}else{
    			$this->assign("mid",$members_info["uid"]);
    			$this->display();
    		}
    	}else{
    		/**
    		 * 将数据插入数据中去
    		 */
    		$data=array();
    		$data["nickname"]=$userdata["nickname"];
    		$data["username"]=$userdata["openid"];
    		$data["logo"]=$userdata["headimgurl"];
    		$data["is_weixin"]=1;
    		if(!empty($uid)){
    			$data["super_uid"]=$uid;
    		}
    		$data["login"]=1;
    		$data["reg_ip"]=get_client_ip(1);
    		$data["reg_time"]=NOW_TIME;
    		$data["status"]=1;
    		$data["update_time"]=NOW_TIME;
    		$addid=D("Members")->add($data);
    		$this->assign("mid",$addid);
    		session("uid",$addid);
    	    $this->display();
    	}
    }
    /**
     * 邦定手机号
     */
    public function saveBindMobile(){
    	$mobile = I("mobile"); //推荐人手机号
    	$code = I("code");
    	$mid = I("mid");   //邦定手机用户
    	if (empty($mobile)) {
    		return $this->error("手机号不能为空");
    	}
    	if (empty($code)) {
    		return $this->error("手机验证码不能为空");
    	}
    	if (!$this->checksmscode($mobile, $code)) {  //验证短信
    		return $this->error("短信验证失败");
    	}
    	if(D("Members")->where(array("uid"=>$mid))->save(array("mobile"=>$mobile))){
    		$this->success("操作成功",U('index'));
    	}else{
    		$this->error("操作失败");
    	}
    
    }
    
    /**
     * 验证短信验证码是否正确
     */
    public function checksmscode($mobile, $code) {
    
    	if ($code == '') {
    		return 0;
    	}
    	session_start();
    	$ucode = md5($mobile . $code); // . '-' . $code;
    	//
    	$ecode = session('sms_code');
    
    	return $ucode == $ecode ? 1 : 0;
    }
    
    public function index(){
    	$uid=session("uid");
    	$info=D("Members")->where(array("uid"=>$uid))->find();
    	$this->assign("info",$info);
    	$this->display();
    }
    
    
    
    /**
     * 微信获取用户登陆信息
     */
   
    public function getAuthorizedUserLoginInfo($sAppId = "wx52e55f5ea4092cc6", $sAppSecret = "968b224d3aed1f8854b00011057fda92") {
      //微信登陆后放到session 中去
    	return array("openid"=>"oWy6FwnD_hHK9S_9utSxXGyX0Hsk","nickname"=>"呆呆","headimgurl"=>"http://wx.qlogo.cn/mmopen/GibK7CQF9aWlJBpN4CexKwrm3cxAruFu0O9aPkj2SdibrGLpZ3FrY2QkrY9vadD80T5r1gdVjGKDpQEYBuzk8jQHucVaRYlDYc/0");
    	$code = isset($_GET['code']) ? trim($_GET['code']) : '';
    	if (empty($code)) {
    		$redirect_uri = $this->GetCurUrl();
    		$state = "";
    		$scope = 'snsapi_userinfo';
    		$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $sAppId . '&redirect_uri=' . rawurlencode($redirect_uri) . '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
    		$this->redirect2($url);
    	} else {
    
    		$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $sAppId . '&secret=' . $sAppSecret . '&code=' . $code . '&grant_type=authorization_code';
    		$result = $this->getCurl($url);
    		$data = json_decode($result, 1);
    		$openid = isset($data['openid']) ? trim(($data['openid'])) : '';
    		if ($openid) {
    			$url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $data["access_token"] . '&openid=' . $openid;
    			$result = $this->getCurl($url);
    			$userdata = json_decode($result, 1);
    			return $userdata;
    		} else {
    			return "";
    		}
    	}
    }
    
    // php获取当前访问的完整url地址
    function GetCurUrl() {
    	$url = 'http://';
    	if (isset($_SERVER ['HTTPS']) && $_SERVER ['HTTPS'] == 'on') {
    		$url = 'https://';
    	}
    	if ($_SERVER ['SERVER_PORT'] != '80') {
    		$url .= $_SERVER ['HTTP_HOST'] . ':' . $_SERVER ['SERVER_PORT'] . $_SERVER ['REQUEST_URI'];
    	} else {
    		$url .= $_SERVER ['HTTP_HOST'] . $_SERVER ['REQUEST_URI'];
    	}
    	// 兼容后面的参数组装
    	if (stripos($url, '?') === false) {
    		$url .= '?t=' . time();
    	}
    	return $url;
    }
    /**
     * 以GET 方式提交
     */
    public function getCurl($url, $second = 30) {
    	$ch = curl_init();
    	//设置超时
    	curl_setopt($ch, CURLOPT_TIMEOUT, $second);
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($ch, CURLOPT_POST, 0);
    	$data = curl_exec($ch);
    	//返回结果
    	if ($data) {
    		curl_close($ch);
    		return $data;
    	} else {
    		$error = curl_errno($ch);
    		curl_close($ch);
    		throw new \WxPayException("curl出错，错误码:$error");
    	}
    }
    
}